package org.soenea.doitall.application.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class PermalinkFilter implements Filter {
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		String command = getCommandFromPathInfoAndMaybeSetSomeAttributes((HttpServletRequest)request);
		((HttpServletRequest)request).setAttribute("command", command);
		
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}
	
	/**
	 * Attempt to extract the command from the request's pathInfo. Note that
	 * this method might set request attributes.
	 * 
	 * @param request
	 * @return null or the command as a simple class name (i.e. not fully
	 *         qualified with the package).
	 */
	private String getCommandFromPathInfoAndMaybeSetSomeAttributes(
			HttpServletRequest request) {
		String path = request.getPathInfo();

		if (path == null)
			return null;

		String command = null;
		if ("/login".equals(path)) {
			command = "Login";
		} else if ("/editgroup".equals(path)) {
			command = "EditGroup";
		}else if ("/creategroup".equals(path)) {
			command = "CreateGroup";
		}else if ("/invitemember".equals(path)) {
			command = "InviteMember";
		}else if ("/logout".equals(path)) {
			command = "LogOut";
		}else if ("/browsegroups".equals(path)) {
			command = "BrowseGroups";
		}else if ("/viewgroup".equals(path)) {
			command = "ViewGroup";
		}else if ("/browseinvite".equals(path)) {
			command = "BrowseInvite";
		}else if ("/deletegroup".equals(path)) {
			command = "DeleteGroup";
		}
		else{
			Pattern pattern = Pattern.compile("^/(acceptinvite|declineinvite|removemember)/(\\d+)$");
			Matcher matcher = pattern.matcher(path);
			
			if (matcher.find()) {
				if (matcher.group(1).equals("acceptinvite"))
					command = "AcceptInvite";
				else if (matcher.group(1).equals("declineinvite"))
					command = "DeclineInvite";
				else if (matcher.group(1).equals("removemember"))
					command = "RemoveMember";
				
				String id = matcher.group(2);
				request.setAttribute("id", id);
			}
		}
		
		
		System.out.println("Command = " + command);
		return command;
	}
}
